﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using StockFinder.Model;

namespace StockFinder.DataAccess
{
    public abstract class DataAccessBase : IDisposable   
    {
        private SqlConnection _SqlConnection;

        protected SqlConnection CreateConnection()
        {
            if (_SqlConnection == null)
            {
                _SqlConnection = new SqlConnection(ApplicationConfiguation.DatabaseConnectionString);

            }

            return _SqlConnection;
        }

        protected SqlConnection CreateOpenConnection()
        {
            _SqlConnection = CreateConnection();

            if (_SqlConnection.State != System.Data.ConnectionState.Open)
            {
                _SqlConnection.Open();
            }

            return _SqlConnection;
        }

        protected void CloseConnection()
        {
            _SqlConnection.Close();
            _SqlConnection.Dispose();
        }


        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _SqlConnection.Close();
                _SqlConnection.Dispose();
            }
        }

        ~DataAccessBase()
        {
            Dispose(false);
        }

        #endregion
    }
}
